/**
 * 日志告警历史服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Between } from 'typeorm';
import { LogAlertHistory } from './entities/log-alert-history.entity';
import { LogAlertConfigDto } from './dto/log-alert-config.dto';

@Injectable()
export class LogAlertHistoryService {
  constructor(
    @InjectRepository(LogAlertHistory)
    private readonly logAlertHistoryRepository: Repository<LogAlertHistory>,
  ) {}

  /**
   * 创建告警历史记录
   * @param config 告警配置
   * @param actualCount 实际触发数量
   * @param status 通知状态
   * @param error 错误信息
   */
  async create(
    config: LogAlertConfigDto,
    actualCount: number,
    status: number = 1,
    error?: string,
  ): Promise<LogAlertHistory> {
    const history = this.logAlertHistoryRepository.create({
      name: config.name,
      type: config.type,
      level: config.level,
      threshold: config.threshold,
      actual_count: actualCount,
      time_window: config.timeWindow,
      notify_channels: config.notifyChannels,
      receivers: config.receivers,
      status,
      error,
    });

    return await this.logAlertHistoryRepository.save(history);
  }

  /**
   * 查询告警历史
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @returns Promise<LogAlertHistory[]> 告警历史列表
   */
  async findByTimeRange(startTime: Date, endTime: Date): Promise<LogAlertHistory[]> {
    return await this.logAlertHistoryRepository.find({
      where: {
        created_at: Between(startTime, endTime),
      },
      order: {
        created_at: 'DESC',
      },
    });
  }

  /**
   * 获取最近的告警历史
   * @param limit 限制数量
   * @returns Promise<LogAlertHistory[]> 告警历史列表
   */
  async findRecent(limit: number = 10): Promise<LogAlertHistory[]> {
    return await this.logAlertHistoryRepository.find({
      order: {
        created_at: 'DESC',
      },
      take: limit,
    });
  }

  /**
   * 统计告警历史
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @returns Promise<{ total: number; success: number; failed: number }> 统计结果
   */
  async getStatistics(startTime: Date, endTime: Date): Promise<{
    total: number;
    success: number;
    failed: number;
  }> {
    const histories = await this.findByTimeRange(startTime, endTime);
    const total = histories.length;
    const success = histories.filter(h => h.status === 1).length;
    const failed = total - success;

    return {
      total,
      success,
      failed,
    };
  }
} 